﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevTeam;

using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Araclar
{
    public partial class ConcurrencySolver : XPopupForm
    {
        public int PK;
        public string TableName;
        public string PKCol;
        DataTable dtResult = null;

        public string Log;
        List<string> UpdateEdilecekler = null;
        public ConcurrencySolver(DataRow dr)
        {

            try
            {

                InitializeComponent();

                btnSave.ItemClick += btnSave_ItemClick;
                gvDegistirilmis.OptionsSelection.EnableAppearanceFocusedRow = false;
                gvDegistirmekIstedigin.OptionsSelection.EnableAppearanceFocusedRow = false;

                gvDegistirilmis.OptionsSelection.EnableAppearanceFocusedCell = false;
                gvDegistirmekIstedigin.OptionsSelection.EnableAppearanceFocusedCell = false;

                gvDegistirilmis.OptionsView.ColumnAutoWidth = false;
                gvDegistirmekIstedigin.OptionsView.ColumnAutoWidth = false;
                gvSonuc.OptionsView.ColumnAutoWidth = false;

                gvSonuc.Appearance.Row.Font = new System.Drawing.Font(gvSonuc.Appearance.Row.Font, FontStyle.Bold);

                Dictionary<string, string> cols = new Dictionary<string, string>();

                foreach (DataColumn dc in dr.Table.Columns)
                    if (dc.Expression != "")
                    {
                        cols.Add(dc.ColumnName, dc.Expression);
                        dc.Expression = "";
                    }

                DataRow drSendeki = GetRowData(dr, DataRowVersion.Original);
                DataRow drDegistirilmis = GetRowData(GetCurrentRowInDB(dr), DataRowVersion.Default);
                DataRow drDegistirmekIstedigin = GetRowData(dr, DataRowVersion.Current);


                foreach (KeyValuePair<string, string> col in cols)
                    dr.Table.Columns[col.Key].Expression = col.Value;

                gvDegistirilmis.CustomDrawCell += new DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventHandler(gvSendeki_CustomDrawCell);
                gvDegistirmekIstedigin.CustomDrawCell += new DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventHandler(gvSendeki_CustomDrawCell);

                TableName = drDegistirmekIstedigin.Table.TableName;

                gvDegistirilmis.OptionsBehavior.ReadOnly = true;
                gvDegistirmekIstedigin.OptionsBehavior.ReadOnly = true;

                gvDegistirilmis.OptionsBehavior.Editable = false;
                gvDegistirmekIstedigin.OptionsBehavior.Editable = false;

                List<string> colsToDelete = new List<string>();
                UpdateEdilecekler = new List<string>();

                for (int i = 0; i < drDegistirmekIstedigin.Table.Columns.Count; i++)
                {
                    string colName = drDegistirmekIstedigin.Table.Columns[i].ColumnName;

                    if (colName == drDegistirmekIstedigin.Table.PrimaryKey[0].ColumnName)
                    {
                        PK = (int)dr[colName];
                        PKCol = colName;
                        colsToDelete.Add(colName);
                        System.Diagnostics.Debug.WriteLine("PK:" + colName);
                    }
                    else if (drSendeki[colName].ToStr() == drDegistirmekIstedigin[colName].ToStr())
                    {
                        colsToDelete.Add(colName);
                        System.Diagnostics.Debug.WriteLine("Değişiklik yok:" + colName);
                    }
                    else if (drDegistirilmis.Table.Columns[colName] == null) //Sonradan eklenen computed sütunlar
                    {
                        colsToDelete.Add(colName);
                        System.Diagnostics.Debug.WriteLine("Değiştirilmişte yok:" + colName);
                    }
                    else if (drDegistirilmis[colName].ToStr() == drDegistirmekIstedigin[colName].ToStr()) //Update edilmeli
                    {
                        colsToDelete.Add(colName);
                        System.Diagnostics.Debug.WriteLine("Aynı değişik:" + colName);
                    }
                    else if (drSendeki[colName].ToStr() == drDegistirilmis[colName].ToStr())
                    {
                        UpdateEdilecekler.Add(colName);
                        //colsToDelete.Add(colName);
                    }

                    //else
                    //{
                    //    //Çakışan sütunlar
                    //}
                }


                drSendeki.Table.PrimaryKey = null;
                drDegistirilmis.Table.PrimaryKey = null;
                drDegistirmekIstedigin.Table.PrimaryKey = null;

                colsToDelete.Add("ModifiedOn");
                colsToDelete.Add("InsertedOn");
                colsToDelete.Add("TS");

                foreach (string colName in colsToDelete)
                {
                    if (drDegistirilmis.Table.Columns[colName] != null)
                        drDegistirilmis.Table.Columns.Remove(colName);

                    if (drSendeki.Table.Columns[colName] != null)
                        drSendeki.Table.Columns.Remove(colName);

                    if (drDegistirmekIstedigin.Table.Columns[colName] != null)
                        drDegistirmekIstedigin.Table.Columns.Remove(colName);
                }



                gcDegistirmekIstedigin.DataSource = drDegistirmekIstedigin.Table;
                gcDegistirilmis.DataSource = drDegistirilmis.Table;
                gcSendeki.DataSource = drSendeki.Table;

                dtResult = drDegistirilmis.Table.Clone();
                DataRow drResult = dtResult.NewRow();

                for (int i = 0; i < drDegistirmekIstedigin.Table.Columns.Count; i++)
                    drResult[i] = drDegistirmekIstedigin[i];

                dtResult.Rows.Add(drResult);
                gcSonuc.DataSource = dtResult;

                foreach (GridColumn col in gvDegistirmekIstedigin.Columns)
                    MapGridColumn(col);
                foreach (GridColumn col in gvDegistirilmis.Columns)
                    MapGridColumn(col);
                foreach (GridColumn col in gvSonuc.Columns)
                    MapGridColumn(col);
                foreach (GridColumn col in gvSendeki.Columns)
                    MapGridColumn(col);

                gvDegistirilmis.BestFitColumns();
                gvDegistirmekIstedigin.BestFitColumns();
                gvSonuc.BestFitColumns();

                txtInfo.Caption = string.Format("{0}: {1}", PKCol, PK);

                gvDegistirmekIstedigin.SetViewCaption("Sizin değiştirmek istediğiniz hali");
                gvDegistirilmis.SetViewCaption("Başkasının değiştirdiği hali");
                gvSonuc.SetViewCaption("KAYDEDİLECEK HALİ");
                gvSendeki.SetViewCaption("Sizdeki ilk hali");


                if (drSendeki.Table.Columns.Count - UpdateEdilecekler.Count == 0)
                {
                    GenerateUpdate();
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }




        void gvSendeki_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            var current = dtResult.Rows[0][e.Column.FieldName].ToString();

            if (current == e.CellValue.ToString())
                e.Appearance.BackColor = Color.SkyBlue;
            else
                e.Appearance.BackColor = Color.White;
        }

        private DataRow GetCurrentRowInDB(DataRow cr)
        {
            string sql = "select * from " + cr.Table.TableName + " where " + cr.Table.PrimaryKey[0].ColumnName + " = " + cr[cr.Table.PrimaryKey[0].ColumnName];
            DataRow dr = Session.DataManager.ExecuteDataTableByQuery(sql).Rows[0];
            return GetRowData(dr, DataRowVersion.Default);
        }

        private DataRow GetRowData(DataRow dr, DataRowVersion RowVersion)
        {
            DataTable dt = dr.Table.Clone();
            DataRow drNew = dt.NewRow();
            for (int i = 0; i < dr.ItemArray.Length; i++)
            {
                drNew[i] = dr[i, RowVersion];
            }
            dt.Rows.Add(drNew);
            return drNew;
        }


        public string Sql = string.Empty;
        void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvDegistirilmis.EndEditing();
            gvSonuc.EndEditing();
            gvDegistirmekIstedigin.EndEditing();
            DialogResult result = XtraMessageBox.Show("Başka birinin yaptığı değişikliğin üzerine yazıyor olabilirsiniz. Bu değişikliği onaylıyor musunuz?", "Dikkat", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

            if (result == System.Windows.Forms.DialogResult.Cancel)
                return;
            else
            {
                GenerateUpdate();

                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
        }

        private void GenerateUpdate()
        {
            string up1 = "update " + TableName + " set ";
            string up2 = "";

            System.Globalization.CultureInfo ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");

            if (dtResult.Columns.Count + UpdateEdilecekler.Count == 0)
                up1 = "";
            else
            {
                for (int i = 0; i < dtResult.Columns.Count; i++)
                {
                    DataColumn dc = dtResult.Columns[i];

                    DataRow dr = dtResult.Rows[0];
                    string colName = dc.ColumnName;

                    if (dc.DataType == typeof(decimal))
                    {
                        up2 += colName + " = " + ((decimal)dr[colName]).ToString(ci) + ", ";
                    }
                    else if (dc.DataType == typeof(DateTime))
                    {
                        DateTime dt = (DateTime)dr[colName];
                        string strDate = dt.ToString("yyyy.MM.dd HH:mm:ss:dd");

                        up2 += colName + " = '" + strDate + "', ";
                    }
                    else
                        up2 += colName + " = '" + dr[colName].ToString() + "', ";
                }
            }

            up2 = up2.Remove(up2.Length - 2) + " where " + PKCol + " = " + PK.ToString();
            Sql = up1 + up2 + " select * from " + TableName + " where " + PKCol + " = " + PK.ToString();
        }

        private void gvDegistirilmis_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            string col = e.Column.FieldName;
            string val = e.CellValue.ToString();

            dtResult.Rows[0][col] = val;

            gvDegistirilmis.Invalidate();
            gvDegistirmekIstedigin.Invalidate();
        }

        private void ConcurrencySolver_FormClosing(object sender, FormClosingEventArgs e)
        {
            //int id = LogManager.TakeScreenShot();
            //Log = string.Format("Tablo:{0} | {1}:{2} | ScreenshotId:{3} | SQL:{4} | Result:", TableName, PKCol, PK, id, Sql);
        }

        private void ConcurrencySolver_Load(object sender, EventArgs e)
        {
            FooterText = "Lütfen geçerli kılmak istediğiniz hücrelere tıklayınız.";
        }
    }
}